package com.itheima.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishDto;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.IDishFlavorService;
import com.itheima.service.IDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/dish")
@Transactional
public class DishController {
    @Autowired
    private IDishService dishService;
    @Autowired
    private IDishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R addDish(@RequestBody DishDto dishDto) {

        dishService.save(dishDto);


        Long dishid = dishDto.getId();


        List<DishFlavor> flavors = dishDto.getFlavors();


        if (flavors != null && flavors.size() > 0) {


            for (DishFlavor flavor : flavors) {

                flavor.setDishId(dishid);
                dishFlavorService.save(flavor);

            }
            return R.success("添加成功");

        } else {
            return R.error("添加失败");
        }

    }

    @GetMapping("/page")
    public R pageQuery(Integer page, Integer pageSize, String name) {
        IPage<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(!(StringUtils.isEmpty(name)), Dish::getName, name);
        dishService.page(pageInfo, qw);
        long total = pageInfo.getTotal();
        List<Dish> records = pageInfo.getRecords();


        HashMap<Object, Object> map = new HashMap<>();
        map.put("total", total);
        List<DishDto> dishDtos = new ArrayList<>();
        for (Dish dish : records) {
            //获取菜品分类id
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //获取到了当前分类的名称
            String categoryName = category.getName();
            // 新建一个DishDto 将分类名称set进入
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            // 还需要将Dish dish 数据放入到 DishDto dishDto 里面
            BeanUtils.copyProperties(dish, dishDto);
            dishDtos.add(dishDto);
        }
        map.put("records", records);
        return R.success(map);


    }

    @GetMapping("/{id}")
    public R selectDish(@PathVariable Long id) {
//1、查询菜品数据 select * from dish where id = ?
        Dish dish = dishService.getById(id);
        //System.out.println(byId);
//2、查询菜品对应的口味数据 select * from dish_flavor where dish_id = ?
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(!(StringUtils.isEmpty(String.valueOf(id))), DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(qw);
        //System.out.println(one);
//返回DishDto对象，先new出该对象 DishDto dishDto = new DishDto();
        DishDto dishDto = new DishDto();


// 把dish菜品数据 赋值/拷贝 给 dishDto对象 BeanUtils.copyProperties

        // 还需要将Dish dish 数据放入到 DishDto dishDto 里面
        BeanUtils.copyProperties(dish, dishDto);

// 设置dishDto的口味数据 dishDto.setFlavors(xxx)
        dishDto.setFlavors(dishFlavors);
// 返回数据 ;
        return R.success(dishDto);
    }

    @PutMapping
    public R updateDish(@RequestBody DishDto dishDto) {
// 1、修改菜品dish表的数据
        boolean update = dishService.updateById(dishDto);

        Long dishId = dishDto.getId();

//取出菜品id Long dishId = dishDto.getId();
// 2、修改菜品的口味数据 如何完成？？
// 2.1 先删除原有的口味数据: delete from dish_flavor where dish_id = ?
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, dishId);
        dishFlavorService.remove(qw);
        List<DishFlavor> flavors = dishDto.getFlavors();
        if (flavors != null && flavors.size() > 0) {
// 2.2 添加菜品口味数据 List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            //添加当前提交过来的口味数据---dish_flavor表的insert操作
            flavor.setDishId(dishDto.getId());


            dishFlavorService.save(flavor);

        }
        return R.success("添加成功");

    } else

    {
        return R.error("添加失败");
    }

}

    @DeleteMapping
    public R deleteByIds(@RequestParam List<Long> ids) {


        boolean b = true;
        for (Long id : ids) {
            b = dishService.removeById(id);
        }
        if (b) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }

    }

    @PostMapping("/status/{status}")
    public R updateByIds(@PathVariable Integer status,
                         @RequestParam List<Long> ids) {
        boolean update =true;
        for (Long id : ids) {
            LambdaUpdateWrapper<Dish> uw = new LambdaUpdateWrapper();
            uw.eq(Dish::getId, id);
            uw.set(Dish::getStatus, status);
             update= dishService.update(uw);

    }
        if (update){
            return R.success("操作成功");
        }
        return R.error("操作失败");
    }

    @GetMapping("/list")
    public R<List<DishDto>> listQuery(Long categoryId,Integer status){
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId,categoryId);
        qw.eq(Dish::getStatus,status);
       List<Dish> list = dishService.list(qw);
        List<DishDto> dishflavor = new ArrayList<>();
        for (Dish dish : list) {

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            LambdaUpdateWrapper<DishFlavor> qw1 = new LambdaUpdateWrapper<>();
            qw1.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> flavors = dishFlavorService.list(qw1);
            //3.将菜品的口味列表 set给 dishDto
            dishDto.setFlavors(flavors);
            //4.将dishDto放入到 dishDtos 集合中
            dishflavor.add(dishDto);
        }
        return list==null?R.error("查询失败"):R.success(dishflavor);

    }


}






